package com.helin.helinhealth.controller;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.helin.helinhealth.common.Result;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@RestController
@RequestMapping("/api/test")
public class TestController {
    
    // 手动添加日志对象，避免@Slf4j注解问题
    private static final Logger log = LoggerFactory.getLogger(TestController.class);

    @GetMapping("/create-file")
    public Result createTestFile() {
        String filePath = "./exports/test_manual.xlsx";
        
        try {
            // 确保目录存在
            File directory = new File("./exports");
            if (!directory.exists()) {
                boolean created = directory.mkdirs();
                log.info("目录创建: {}", created);
            }
            
            log.info("开始创建Excel文件: {}", filePath);
            Workbook workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet("Test Sheet");
            
            // 创建表头
            Row headerRow = sheet.createRow(0);
            headerRow.createCell(0).setCellValue("ID");
            headerRow.createCell(1).setCellValue("Name");
            headerRow.createCell(2).setCellValue("Value");
            
            // 添加数据
            for (int i = 1; i <= 5; i++) {
                Row row = sheet.createRow(i);
                row.createCell(0).setCellValue(i);
                row.createCell(1).setCellValue("Test " + i);
                row.createCell(2).setCellValue(i * 10);
            }
            
            // 自动调整列宽
            for (int i = 0; i < 3; i++) {
                sheet.autoSizeColumn(i);
            }
            
            // 写入文件
            try (FileOutputStream fileOut = new FileOutputStream(filePath)) {
                workbook.write(fileOut);
                fileOut.flush();
                log.info("Excel文件写入内容完成");
            }
            workbook.close();
            
            // 检查文件是否创建成功
            File checkFile = new File(filePath);
            if (checkFile.exists()) {
                log.info("Excel文件创建成功: {}, 大小: {} 字节", filePath, checkFile.length());
                return Result.success("文件创建成功，路径: " + filePath + ", 大小: " + checkFile.length() + " 字节");
            } else {
                log.error("文件创建失败，文件不存在: {}", filePath);
                return Result.error("文件创建失败，文件不存在");
            }
        } catch (IOException e) {
            log.error("创建测试文件失败", e);
            return Result.error("创建测试文件失败: " + e.getMessage());
        }
    }
    
    @GetMapping("/download-excel")
    public ResponseEntity<byte[]> downloadExcel() {
        String filePath = "./exports/test_manual.xlsx";
        
        try {
            log.info("开始下载Excel文件: {}", filePath);
            Path path = Paths.get(filePath);
            if (!Files.exists(path)) {
                log.error("文件不存在: {}", path.toAbsolutePath());
                throw new IOException("文件不存在: " + path.toAbsolutePath());
            }
            
            // 读取文件内容
            byte[] fileContent = Files.readAllBytes(path);
            log.info("文件读取成功，大小: {} 字节", fileContent.length);
            
            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"));
            headers.setContentDispositionFormData("attachment", "downloaded_test.xlsx");
            headers.setContentLength(fileContent.length);
            
            return ResponseEntity.ok()
                    .headers(headers)
                    .body(fileContent);
        } catch (IOException e) {
            log.error("下载文件失败: {}", e.getMessage(), e);
            throw new RuntimeException("下载文件失败: " + e.getMessage());
        }
    }
} 